package com.roc.web.action.settlement;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblTransJnlsSettle;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

/**
 * 结算信息查询
 * @author malei
 * 20161205
 *
 */
@Component
@Scope("prototype")
@Namespace("/settlement")
public class SettlementInfoAction extends PaginationBaseAction{
	private Logger log = LogManager.getLogger(SettlementInfoAction.class);
	private SettleInfoSearchCondition searchCondition;
	@Autowired 
	private IMerchantServices merchantServices;
	
	@Autowired
	private IPagenitionService pagenitionService;
	
	@Autowired
	private IExcelService excelService;
	
	@Autowired
	private IPowerInfoService powerInfoService;
	
	private InputStream excelFile;
	
	@Action(value="querySettleInfoJsp",results={@Result(name="success",location="/pages/settlement/settlementList.jsp")})
	public String querySettleInfoJsp() throws Exception{
		return SUCCESS;
	}
	
	@Action(value="querySettlementList",results={@Result(name="success",location="/pages/settlement/settlementList.jsp")})
	public String querySettlementList() throws Exception{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(searchCondition==null){
				searchCondition = (SettleInfoSearchCondition) getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition= new SettleInfoSearchCondition();
				}
			}
			if("".equals(Constance.Null2EmptyTrim(searchCondition.getMinDate())) || "".equals(Constance.Null2EmptyTrim(searchCondition.getMaxDate()))){
				log.info("结算查询查询条件日期为空");
				return SUCCESS;
			}
			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
	           // String orgCode=map.get("orgCode");
	            String superRole= map.get("superRole");
	            String opRealId =map.get("opRealId");
			//当登录人员为代理商时，查询他的子代理
			searchCondition.setRoleType(superRole);
			if(Role.MERCHANT.getCode().equals(superRole)){
				searchCondition.setBusinessNum(logingMerchant.getAccountNo());
			}else if(Role.AGENT.getCode().equals(superRole)||Role.SFB_AGENT.getCode().equals(superRole)){
				
				String agentId=opRealId;
				searchCondition.setAgentId(agentId);
				
			}else if(Role.AGENT_BUSS.getCode().equals(superRole)){
				searchCondition.setOpId(opRealId);
			}else if(Role.MARKET_DIRECT.getCode().equals(superRole) || Role.MARKET_LEAD.getCode().equals(superRole)){
				searchCondition.setMarketorId(opRealId);
			}else if(Role.O_MANAGER.getCode().equals(superRole)){//
				searchCondition.setUcbccdArea(logingMerchant.getOneagentid());
			}/*else if(Role.OPERATORS_COMM.getCode().equals(logingMerchant.getRoleType()) && !Constant.SD_ORG_CD.equals(logingMerchant.getOneagentid())){//运维人员
				searchCondition.setUcbccdArea(logingMerchant.getOneagentid());
			}*/else{
				searchCondition.setOrgCode(logingMerchant.getOrgCode());
			}
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<TblTransJnlsSettle> posserList = new ArrayList<TblTransJnlsSettle>();
			dealTheSearchRsList(searchRsList,posserList);
			
			getRequest().setAttribute("posserList", posserList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (Exception e) {
			log.error("查询结算信息异常："+e);
		}
		return SUCCESS;
	}
	
	@Action(value="exportSettlementList",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/settlement/settlementList.jsp") })
	public String exportSettlementList(){
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(searchCondition==null){
				searchCondition = (SettleInfoSearchCondition) getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition= new SettleInfoSearchCondition();
				}
			}
			if("".equals(Constance.Null2EmptyTrim(searchCondition.getMinDate())) || "".equals(Constance.Null2EmptyTrim(searchCondition.getMaxDate()))){
				log.info("结算导出导出条件时间为空");
				return ERROR;
			}
			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
	           // String orgCode=map.get("orgCode");
	            String superRole= map.get("superRole");
	            String opRealId =map.get("opRealId");
			//当登录人员为代理商时，查询他的子代理
			searchCondition.setRoleType(superRole);
			if(Role.MERCHANT.getCode().equals(superRole)){
				searchCondition.setBusinessNum(logingMerchant.getAccountNo());
			}else if(Role.AGENT.getCode().equals(superRole)||Role.SFB_AGENT.getCode().equals(superRole)){
				
				String agentId=opRealId;
				searchCondition.setAgentId(agentId);
				
			}else if(Role.AGENT_BUSS.getCode().equals(superRole)){
				searchCondition.setOpId(opRealId);
			}else if(Role.MARKET_DIRECT.getCode().equals(superRole) || Role.MARKET_LEAD.getCode().equals(superRole)){
				searchCondition.setMarketorId(opRealId);
			}else if(Role.O_MANAGER.getCode().equals(superRole)){//
				searchCondition.setUcbccdArea(logingMerchant.getOneagentid());
			}/*else if(Role.OPERATORS_COMM.getCode().equals(logingMerchant.getRoleType()) && !Constant.SD_ORG_CD.equals(logingMerchant.getOneagentid())){//运维人员
				searchCondition.setUcbccdArea(logingMerchant.getOneagentid());
			}*/else{
				searchCondition.setOrgCode(logingMerchant.getOrgCode());
			}
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			List<TblTransJnlsSettle> posserList = new ArrayList<TblTransJnlsSettle>();
			dealTheSearchRsList(searchRsList,posserList);
			
			HSSFWorkbook work=excelService.exportSettlementFlow(posserList,searchCondition.getMinDate(),searchCondition.getMaxDate());

			 ByteArrayOutputStream output = new ByteArrayOutputStream();  
			         work.write(output);  
			   
			        byte[] ba = output.toByteArray();  
			         excelFile = new ByteArrayInputStream(ba);  
			         output.flush();  
			         output.close();
			
		}catch(Exception e){
			log.error("导出结算信息异常："+e);
		}
		return SUCCESS;
	}

	private void dealTheSearchRsList(List<Object> searchRsList,
			List<TblTransJnlsSettle> posserList) {
		if(searchRsList != null && searchRsList.size()>0){
			Iterator it = searchRsList.iterator();
			while(it.hasNext()){
				Object[] obj = (Object[]) it.next();
				TblTransJnlsSettle onePosser = new TblTransJnlsSettle();
				onePosser.setMchtCd(Constance.Null2EmptyTrim(obj[0]));
				onePosser.setMchtName(Constance.Null2EmptyTrim(obj[1]));
				onePosser.setMchtSetAmt(new BigDecimal(Constance.Null2EmptyTrim(obj[2])).doubleValue());
				onePosser.setMchtFee(new BigDecimal(Constance.Null2EmptyTrim(obj[3])).doubleValue());
				onePosser.setAccountName(Constance.Null2EmptyTrim(obj[4]));
				onePosser.setBankName(Constance.Null2EmptyTrim(obj[5]));
				onePosser.setAccount(Constance.Null2EmptyTrim(obj[6]));
				onePosser.setSettleDate(Constance.Null2EmptyTrim(obj[7]));
				posserList.add(onePosser);
			}
		}
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_QUERY_SETTLEMENT, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (SettleInfoSearchCondition)getSession().getAttribute(SEARCH_SESSION_QUERY_SETTLEMENT);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}
	
	public String getExcelName() {
		String excelName="结算详情"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				//e.printStackTrace();
				log.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}

	public SettleInfoSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(SettleInfoSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	
	
	
}
